<template>
  <view class="normal-login-container">
    <view class="logo-content align-center justify-center flex">
      <view class="box-bg">
        <image mode="" src="@/static/images/logoIcon.png"></image>
        <view class="logo-manifesto">
          <p class="title">让协作高效</p>
          <text>Make It Efficient</text>
        </view>
      </view>
    </view>
    <view class="login-form-content">
      <view class="input-item flex align-center">
        <view class="iconfont icon-user icon"></view>
        <input
          v-model="loginForm.username"
          adjust-position
          class="input"
          maxlength="30"
          placeholder="请输入账号"
          type="text"
        />
      </view>
      <view class="input-item flex align-center">
        <view class="iconfont icon-password icon"></view>
        <input
          v-model="loginForm.password"
          adjust-position
          class="input"
          maxlength="20"
          placeholder="请输入密码"
          type="password"
        />
        <p
          :class="{ activeColor: jizhumima }"
          style="width: 100%; text-align: right; margin-right: 32rpx; color: #0081ff"
          @tap="jizhumimaFn"
        >
          记住密码
        </p>
      </view>
      <view
        v-if="captchaEnabled"
        class="input-item flex align-center"
        style="width: 60%; margin: 0px"
      >
        <view class="iconfont icon-code icon"></view>
        <input
          v-model="loginForm.code"
          adjust-position
          class="input"
          maxlength="4"
          placeholder="请输入验证码"
          type="number"
        />
        <view class="login-code">
          <image :src="codeUrl" class="login-code-img" @click="getCode"></image>
        </view>
      </view>
      <view class="action-btn">
        <button class="login-btn cu-btn block bg-blue lg round" @click="handleLogin">登录</button>
      </view>
      <view v-if="register" class="reg text-center">
        <text class="text-grey1">没有账号？</text>
        <text class="text-blue" @click="handleUserRegister">立即注册</text>
      </view>
      <view class="xieyi text-center">
        <checkbox-group @change="checkboxChange">
          <checkbox :checked="isAgree" />
          我同意
        </checkbox-group>
        <!-- <text class="text-grey1">登录即代表同意</text> -->
        <text class="text-blue" @click="handleUserAgrement">《用户协议》</text>
        和
        <text class="text-blue" @click="handlePrivacy">《隐私协议》</text>
      </view>
    </view>
  </view>
</template>

<script>
import { getCodeImg, getNewVersionApi } from '@/api/login'

export default {
  data() {
    return {
      isAgree: false, //是否同意
      codeUrl: '',
      captchaEnabled: true,
      jizhumima: false,
      // 用户注册开关
      register: false,
      globalConfig: getApp().globalData.config,
      loginForm: {
        username: null,
        password: null,
        code: '',
        uuid: '',
      },
    }
  },
  created() {
    this.getCode()
    uni.loadFontFace({
      family: 'jinbu',
      source: 'url("/static/font/DingTalk JinBuTi.ttf")',
    })

    // #ifdef APP-PLUS
    uni.loadFontFace({
      family: 'jinbu',
      source: `url(${plus.io.convertLocalFileSystemURL('/static/font/DingTalk JinBuTi.ttf')})`,
    })
    // #endif
  },
  mounted() {
    if (uni.getStorageSync('jizhumima')) {
      let { username, password } = uni.getStorageSync('userLoginInfo') || null
      this.loginForm.username = username || null
      this.loginForm.password = password || null
      this.jizhumima = true
    } else {
      uni.setStorageSync('jizhumima', this.jizhumima)
      this.jizhumima = false
    }
    this.getNewVersionApiFn()
  },
  methods: {
    checkboxChange() {
      this.isAgree = !this.isAgree
    },
    getAppInfo() {
      return new Promise((resolve, reject) => {
        try {
          const systemInfo = uni.getSystemInfoSync() // 获取系统信息
          let appVersion = '未知' // 默认值
          // 判断平台
          if (systemInfo.platform === 'h5') {
            // H5 平台
            appVersion = systemInfo.appVersion || 'H5 无版本号'
          } else if (systemInfo.platform === 'android' || systemInfo.platform === 'ios') {
            if (typeof plus !== 'undefined') {
              appVersion = systemInfo.appWgtVersion || 'App 无版本号'
            }
          }
          // 返回结果
          resolve({
            platform: systemInfo.platform, // 平台信息（h5/android/ios）
            appVersion: appVersion, // 应用版本号
            os: systemInfo.osName || systemInfo.platform, // 操作系统（iOS/Android）
            osVersion: systemInfo.system, // 操作系统版本
            deviceModel: systemInfo.model, // 设备型号
          })
        } catch (err) {
          reject('获取应用信息失败: ' + err.message)
        }
      })
    },
    // 跳转到浏览器页面
    openExternal(url) {
      if (url) {
        // 获取当前平台
        const platform = uni.getSystemInfoSync().platform
        if (platform === 'h5') {
          // H5 平台使用 window.open
          window.open(url)
        } else if (platform === 'android' || platform === 'ios') {
          // App 平台使用 plus.runtime.openURL
          if (typeof plus !== 'undefined') {
            plus.runtime.openURL(url, (err) => {
              if (err) {
                uni.showToast({
                  title: '打开浏览器失败',
                  icon: 'none',
                })
                console.error('打开浏览器失败:', err)
              }
            })
          } else {
            uni.showToast({
              title: '当前环境不支持跳转',
              icon: 'none',
            })
          }
        } else {
          uni.showToast({
            title: '当前平台不支持跳转浏览器',
            icon: 'none',
          })
        }
      } else {
        uni.showToast({
          title: 'URL 不能为空',
          icon: 'none',
        })
      }
    },

    // 调用
    getNewVersionApiFn() {
      this.getAppInfo().then((res) => {
        let { appVersion, os } = res
        let params = {
          version: String(appVersion),
          type: os,
        }
        if (os === 'android') {
          params.type = '1'
        } else if (os === 'ios') {
          params.type = '2'
        }
        getNewVersionApi(params).then((item) => {
          let { data, code } = item
          if (code === 200) {
            if (data && data.isForceUpdate === 0) {
              uni.showModal({
                title: '检测到新版应用',
                content:
                  os === 'ios' ? '请前往App Store搜索金圣龙ERP手动进行更新' : '是否立即更新?',
                success: (res) => {
                  if (res.confirm) {
                    console.log(data, params, '------------------------------')
                    if (os !== 'ios') {
                      this.openExternal(data.url)
                    } else {
                      // 跳转ios appstore
                      plus.runtime.openURL('https://apps.apple.com/us/app/金圣龙ERP/id6742095241')
                    }
                  }
                },
              })
            } else if (data && data.isForceUpdate === 1) {
              uni.showModal({
                title: '检测到新版应用',
                showCancel: false,
                content:
                  os === 'ios'
                    ? '请前往App Store搜索金圣龙ERP手动进行更新'
                    : '版本更新内容重要立即更新！',
                success: (res) => {
                  if (res.confirm) {
                    console.log(data, params, '------------------------------')
                    if (os !== 'ios') {
                      this.openExternal(data.url)
                    } else {
                      // 跳转ios appstore
                      plus.runtime.openURL('https://apps.apple.com/us/app/金圣龙ERP/id6742095241')
                    }
                  }
                },
              })
            }
          }
        })
      })
    },
    // 用户注册
    handleUserRegister() {
      this.$tab.redirectTo(`/pages/register`)
    },
    // 隐私协议
    handlePrivacy() {
      let site = this.globalConfig.appInfo.agreements[0]
      this.$tab.navigateTo(`/pages/common/webview/index?title=${site.title}&url=${site.url}`)
    },
    // 用户协议
    handleUserAgrement() {
      let site = this.globalConfig.appInfo.agreements[1]
      this.$tab.navigateTo(`/pages/common/webview/index?title=${site.title}&url=${site.url}`)
    },
    // 获取图形验证码
    getCode() {
      getCodeImg().then((res) => {
        this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled
        if (this.captchaEnabled) {
          this.codeUrl = 'data:image/gif;base64,' + res.img
          this.loginForm.uuid = res.uuid
        }
      })
    },
    // 登录方法
    async handleLogin() {
      if (this.loginForm.username === '') {
        this.$modal.msgError('请输入您的账号')
      } else if (this.loginForm.password === '') {
        this.$modal.msgError('请输入您的密码')
      } else if (this.loginForm.code === '' && this.captchaEnabled) {
        this.$modal.msgError('请输入验证码')
      } else if (!this.isAgree) {
        this.$modal.msgError('请同意相关协议')
        return
      } else {
        this.$modal.loading('登录中，请耐心等待...')
        this.pwdLogin()
      }
    },
    // 密码登录
    async pwdLogin() {
      this.$store
        .dispatch('Login', this.loginForm)
        .then(() => {
          this.$modal.closeLoading()
          this.loginSuccess()
        })
        .catch(() => {
          if (this.captchaEnabled) {
            this.getCode()
          }
        })
    },
    // 登录成功后，处理函数
    loginSuccess(result) {
      uni.setStorageSync('userLoginInfo', {
        username: this.loginForm.username,
        password: this.loginForm.password,
      })
      // 设置用户信息
      this.$store.dispatch('GetInfo').then((res) => {
        this.$tab.reLaunch('/pages/index')
      })
    },
    jizhumimaFn() {
      this.jizhumima = !this.jizhumima
      uni.setStorageSync('jizhumima', this.jizhumima)
    },
  },
}
</script>

<style lang="scss">
page {
  background-color: #ffffff;
}

:deep(.uni-checkbox-input) {
  width: 28rpx !important;
  height: 28rpx !important;
  margin: 0 10rpx 4rpx 0 !important;
}

.normal-login-container {
  width: 100%;
  background: linear-gradient(200deg, #b3cfff 0%, #dbf0ff 38.19%, #d0ebff 70.36%);
  height: 100vh;

  .logo-content {
    width: 100%;
    font-size: 21px;
    text-align: center;
    padding-top: 40%;

    .box-bg {
      position: relative;
      width: 458rpx;

      image {
        top: -8%;
        left: -5%;
        border-radius: 8rpx;
        position: absolute;
        width: 100%;
        height: 82rpx;
      }

      .logo-manifesto {
        color: #0080ff;

        .title {
          font-size: 76rpx;
          font-family: 'jinbu';
        }

        span {
          font-size: 30rpx;
        }
      }
    }
  }

  .login-form-content {
    text-align: center;
    padding: 64rpx 32rpx 0 32rpx;
    box-sizing: border-box;
    width: 100%;
    position: fixed;
    bottom: 0;
    height: 55%;
    background-color: #fff;
    border-radius: 32rpx 32rpx 0 0;

    .input-item {
      margin: 40rpx auto;
      background-color: #f5f6f7;
      height: 90rpx;
      border-radius: 40rpx;

      .icon {
        font-size: 38rpx;
        margin-left: 20rpx;
        color: #999;
      }

      .input {
        width: 100%;
        font-size: 28rpx;
        line-height: 40rpx;
        text-align: left;
        padding-left: 30rpx;
      }
    }

    .activeColor {
      color: #94bfff !important;
    }

    .login-btn {
      margin-top: 80rpx;
      height: 90rpx;
    }

    .reg {
      margin-top: 30rpx;
    }

    .xieyi {
      color: #333;
      margin-top: 40rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .login-code {
      height: 76rpx;
      float: right;

      .login-code-img {
        height: 76rpx;
        position: absolute;
        margin-left: 20rpx;
        width: 200rpx;
      }
    }
  }
}
</style>
